package com.kfm.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;

@WebServlet("/index")
public class IndexServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        resp.setContentType("text/plain;charset=utf-8");

        Cookie cookie = new Cookie("lastTime", LocalDateTime.now().toString());

        cookie.setMaxAge(60 * 60 * 24 * 7);

        resp.addCookie(cookie);

        Cookie[] cookies = req.getCookies();

        if (cookies != null){
            for (Cookie cookie1 : cookies){
                String name = cookie1.getName();
                if ("lastTime".equals(name)){
                    resp.getWriter().write("欢迎再次访问，上次访问时间为：" + cookie1.getValue());
                    return;
                }
            }
        }

        resp.getWriter().write("欢迎第一次访问");

    }
}
